package zhihui.mobile.ui.express;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zgm.utils.UiUtils;
import com.zgm.utils.ui.UiTextHeader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import zhihui.mobile.R;
import zhihui.mobile.bean.express.ExpressBeanListV2;
import zhihui.mobile.bean.express.ExpressTimeBeanListV2;
import zhihui.mobile.bean.shop.sales.CouponInfo;
import zhihui.mobile.bean.wx.WeixinPayInfo;
import zhihui.mobile.interfaces.net.IHttpCallBackListener;
import zhihui.mobile.manager.express.ExpressManager;
import zhihui.mobile.manager.pay.PayManager;
import zhihui.mobile.manager.user.UserManager;
import zhihui.mobile.presenter.IPresenter;
import zhihui.mobile.ui.BaseFragmentActivity;
import zhihui.mobile.ui.MyOnClickListener;
import zhihui.mobile.ui.shop.coupon.CouponAdapter;

import static java.lang.Double.parseDouble;


/**
 * Created by Administrator on 2017/9/16.
 */

public class ExpressOrderActivity extends BaseFragmentActivity
{

    @Bind(R.id.express_history_title_layout)
    UiTextHeader expressHistoryTitleLayout;
    @Bind(R.id.express_order_rv)
    CustomRecyclerView expressOrderRv;
    @Bind(R.id.express_order_num_rv)
    TextView expressOrderNumRv;
    @Bind(R.id.express_order_tv)
    TextView expressOrderTv;
    @Bind(R.id.express_house_num_edit)
    EditText expressHouseNumEdit;
    @Bind(R.id.express_order_youhui_tv)
    TextView expressOrderYouhuiTv;
    @Bind(R.id.express_order_pay_num_tv)
    TextView expressOrderPayNumTv;
    @Bind(R.id.express_order_paisongfei_tv)
    TextView expressOrderPaisongfeiTv;
    @Bind(R.id.express_order_show_time_tv)
    TextView expressOrderShowTimeTv;
    @Bind(R.id.express_order_show_quan_tv)
    TextView expressOrderShowQuanTv;
    @Bind(R.id.express_order_pay_btn)
    TextView tv_express_order_pay;

    private ExpressOrderAdapter adapter;
    private SelectExpressTimeDialog selectExpressTimeDialog;

    private ExpressTimeBeanListV2 expressTimeBeanList;
    private List<CouponInfo> couponInfos;
    private int couponInfosPosi = -1;

    private int day = 0;
    private int dayHour = -1;
    private int dayHourId = -1;
    private String orderId;

    @Override
    public void initView()
    {


    }

    @Override
    protected int getLayoutResId()
    {
        return R.layout.exprees_order_activity;
    }

    @Override
    protected IPresenter[] getPresenters()
    {
        return new IPresenter[0];
    }

    @Override
    protected void onInitPresenter()
    {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initData();
    }

    private void initData()
    {
        //title数据
        expressHistoryTitleLayout.setTitle("寄包裹");
        expressHistoryTitleLayout.setRightText("");
        expressHistoryTitleLayout.setLeftBottonIcon(R.drawable.shop_back);
        expressHistoryTitleLayout.setLeftButtonOnClickListener(new MyOnClickListener(this)
        {
            @Override
            public void onClick(View v)
            {
                super.onClick(v);
                finish();
            }
        });
        expressOrderTv.setText("收货人:" + UserManager.getInstance().getCurUser().getName() + "  " + UserManager.getInstance().getCurUser().getNo());
        expressOrderRv.setLayoutManager(new LinearLayoutManager(this)
        {
            @Override
            public boolean canScrollVertically()
            {
                return false;
            }
        });
        expressOrderRv.setHasFixedSize(true);
        ArrayList<ExpressBeanListV2.DataBean.InnerBean> dataBeens = (ArrayList<ExpressBeanListV2.DataBean.InnerBean>) getIntent().getExtras().getSerializable("data");

        adapter = new ExpressOrderAdapter(dataBeens, this);
        expressOrderRv.setAdapter(adapter);
        expressOrderNumRv.setText("共计：" + adapter.getData().size() + "个包裹");
        selectExpressTimeDialog = new SelectExpressTimeDialog(this);
    }

    @OnClick({R.id.express_order_time_btn, R.id.express_order_coupon_btn, R.id.express_order_pay_details_btn, R.id.express_order_pay_btn})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.express_order_time_btn:
                selectExpressTimeDialog.createDialog();
                break;
            case R.id.express_order_coupon_btn:
                if (selectExpressTimeDialog.getDay() == 0 || selectExpressTimeDialog.getDayHour() == -1)
                {
                    UiUtils.ToastInCenter(ExpressOrderActivity.this, "请选择派送时间", Toast.LENGTH_SHORT);
                    return;
                }
                CouponDialog();
                break;
            case R.id.express_order_pay_details_btn:
                break;
            case R.id.express_order_pay_btn:
                if (null == expressHouseNumEdit.getText().toString().trim() || expressHouseNumEdit.getText().toString().trim().isEmpty())
                {
                    UiUtils.ToastInCenter(ExpressOrderActivity.this, "请输入门牌号", Toast.LENGTH_SHORT);
                    return;
                }
                if (selectExpressTimeDialog.getDay() == 0 || selectExpressTimeDialog.getDayHour() == -1)
                {
                    UiUtils.ToastInCenter(ExpressOrderActivity.this, "请选择派送时间", Toast.LENGTH_SHORT);
                    return;
                }
                double temp = parseDouble(expressOrderPayNumTv.getText().toString().replace("¥", "").trim());
                int temp2 = (int) (temp * 100);
                if (temp2 == 0)
                {
                    payInfo(temp2, null, null, null);
                    return;
                }

                showPayDialog(this, temp2);
                break;
        }
    }

    /*微信支付*/
    public void showPayDialog(final Context context, final int paymoney)
    {
        final Dialog dialog = new Dialog(context, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(context).inflate(R.layout.shop_pay_dialog, null);
        ImageView iv_close = (ImageView) view.findViewById(R.id.iv_pay_dialog_close);
        TextView tv_money = (TextView) view.findViewById(R.id.tv_pay_dialog_money);
        tv_money.setText("￥" + ((double) paymoney / 100));
        iv_close.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                dialog.dismiss();
            }
        });
        final CheckBox cb_ilpay = (CheckBox) view.findViewById(R.id.cb_pay_dialog_ilpay);
        final CheckBox cb_weixin = (CheckBox) view.findViewById(R.id.cb_pay_dialog_weixin);
        cb_ilpay.setChecked(true);
        cb_weixin.setChecked(false);
        cb_ilpay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if (isChecked)
                {
                    cb_weixin.setChecked(false);
                }
            }
        });

        cb_weixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
            {
                if (isChecked)
                {
                    cb_ilpay.setChecked(false);
                }
            }
        });


        RelativeLayout rl_ilpay = (RelativeLayout) view.findViewById(R.id.rl_pay_dialog_ilpay);
        rl_ilpay.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                cb_weixin.setChecked(false);
            }
        });

        RelativeLayout rl_weixin = (RelativeLayout) view.findViewById(R.id.rl_pay_dialog_weixin);
        rl_weixin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                cb_ilpay.setChecked(false);
            }
        });
        TextView tv_pay = (TextView) view.findViewById(R.id.tv_pay_dialog_pay);
        tv_pay.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (!cb_weixin.isChecked() && !cb_ilpay.isChecked())
                {
                    UiUtils.ToastInCenter(ExpressOrderActivity.this, "请选择支付方式!", Toast.LENGTH_SHORT);
                    return;
                }

                payInfo(paymoney, cb_weixin, dialog, cb_ilpay);
            }
        });

        //布局给Dialog
        dialog.setContentView(view);
        //获取当前Activity窗体
        Window window = dialog.getWindow();
        //设置dialog 从底部弹出
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得窗体属性
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.y = 0;
        window.setAttributes(params);
        dialog.show();
    }

    private void payInfo(final int paymoney, final CheckBox cb_weixin, final Dialog dialog, final CheckBox cb_ilpay)
    {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < adapter.getData().size(); i++)
        {
            if (i == 0)
            {
                stringBuffer.append("" + adapter.getData().get(i).getId_f());
            } else
            {
                stringBuffer.append("," + adapter.getData().get(i).getId_f());
            }
        }
        ExpressManager.getInstance().initApplyOrder(
                new IHttpCallBackListener()
                {
                    @Override
                    public void success(JSONObject result)
                    {
                        try
                        {
                            orderId = result.getString("data");
                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                        }

                        if (paymoney == 0)
                        {
                            UiUtils.ToastInCenter(ExpressOrderActivity.this, "支付成功", Toast.LENGTH_SHORT);
                            finish();
                            return;
                        }

                        if (cb_weixin.isChecked())
                        {
                            PayManager.getInstance().weixin(new IHttpCallBackListener()
                            {
                                @Override
                                public void success(JSONObject result)
                                {
                                    try
                                    {
                                        Gson gson = new Gson();
                                        WeixinPayInfo payInfo = gson.fromJson(result.getJSONObject("data").toString(), WeixinPayInfo.class);
                                        ExpressPayUtils expressPayUtils = new ExpressPayUtils(ExpressOrderActivity.this);
                                        expressPayUtils.weixinPay(payInfo);
                                    } catch (JSONException e)
                                    {
                                        e.printStackTrace();
                                        UiUtils.ToastInCenter(ExpressOrderActivity.this, "解析数据失败", Toast.LENGTH_SHORT);
                                    }
                                }

                                @Override
                                public void failed(String message)
                                {
                                    UiUtils.ToastInCenter(ExpressOrderActivity.this, message, Toast.LENGTH_SHORT);
                                }
                            }, orderId, paymoney);

                            dialog.dismiss();
                            return;
                        }
                        if (cb_ilpay.isChecked())
                        {
                            PayManager.getInstance().ilpay(new IHttpCallBackListener()
                            {
                                @Override
                                public void success(JSONObject result)
                                {
                                    try
                                    {
                                        String data = result.getString("data");
                                        ExpressPayUtils expressPayUtils = new ExpressPayUtils(ExpressOrderActivity.this);
                                        expressPayUtils.ilPay(data);
                                    } catch (JSONException e)
                                    {
                                        e.printStackTrace();
                                        UiUtils.ToastInCenter(ExpressOrderActivity.this, "解析数据失败", Toast.LENGTH_SHORT);
                                    }
                                }

                                @Override
                                public void failed(String message)
                                {
                                    UiUtils.ToastInCenter(ExpressOrderActivity.this, message, Toast.LENGTH_SHORT);
                                }
                            }, orderId, paymoney);
                            dialog.dismiss();
                            return;
                        }


                    }

                    @Override
                    public void failed(String message)
                    {
                        UiUtils.ToastInCenter(ExpressOrderActivity.this, message, Toast.LENGTH_SHORT);
                    }
                },
                UserManager.getInstance().getCurUser().getStore(),
                UserManager.getInstance().getCurUser().getName(),
                UserManager.getInstance().getCurUser().getTel(),
                expressHouseNumEdit.getText().toString().trim(),
                stringBuffer.toString(),
                paymoney,
                day,
                dayHourId,
                null == couponInfos || couponInfos.size() == 0 ? -1 : couponInfos.get(couponInfosPosi).getCouponId());
    }


    /*优惠券*/
    private void CouponDialog()
    {
        ExpressManager.getInstance().initFindFreightCouponByUserId(new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                Gson gson = new Gson();
                try
                {
                    couponInfos = gson.fromJson(result.getJSONArray("data").toString(), new TypeToken<List<CouponInfo>>()
                    {
                    }.getType());
                    if (couponInfos != null && couponInfos.size() > 0)
                    {
                        final Dialog dialog = new Dialog(ExpressOrderActivity.this, R.style.ActionSheetDialogStyle);
                        View view = LayoutInflater.from(ExpressOrderActivity.this).inflate(R.layout.shop_coupon_dialog, null);
                        ImageView iv_close = (ImageView) view.findViewById(R.id.iv_coupon_dialog_close);
                        iv_close.setOnClickListener(new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                dialog.dismiss();
                            }
                        });
                        ListView lv_content = (ListView) view.findViewById(R.id.lv_shop_coupon_dialog_content);
                        CouponAdapter adapter = new CouponAdapter(ExpressOrderActivity.this);
                        adapter.setList(couponInfos);
                        lv_content.setAdapter(adapter);
                        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener()
                        {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                            {
                                couponInfosPosi = position;
                                double result = Double.parseDouble(expressOrderPaisongfeiTv.getText().toString().replace("¥", "").trim()) - (double) couponInfos.get(position).getDiscount() / 100;
                                expressOrderYouhuiTv.setText("¥ " + new DecimalFormat("#0.00").format(couponInfos.get(position).getDiscount() / 100));
                                expressOrderPayNumTv.setText("¥ " + new DecimalFormat("#0.00").format(result >= 0 ? result : 0.00));
                                expressOrderShowQuanTv.setText("已选 " + couponInfos.get(position).getDescription());
                                dialog.dismiss();
                            }
                        });
                        //布局给Dialog
                        dialog.setContentView(view);
                        //获取当前Activity窗体
                        Window window = dialog.getWindow();
                        //设置dialog 从底部弹出
                        window.setGravity(Gravity.BOTTOM);
                        window.getDecorView().setPadding(0, 0, 0, 0);
                        //获得窗体属性
                        WindowManager.LayoutParams params = window.getAttributes();
                        params.width = WindowManager.LayoutParams.MATCH_PARENT;
                        params.y = 0;
                        window.setAttributes(params);
                        dialog.show();

                    } else
                    {
                        UiUtils.ToastInCenter(ExpressOrderActivity.this, "没有可用优惠券", Toast.LENGTH_SHORT);
                    }
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    UiUtils.ToastInCenter(ExpressOrderActivity.this, "解析数据失败", Toast.LENGTH_SHORT);
                }

            }

            @Override
            public void failed(String message)
            {
                UiUtils.ToastInCenter(ExpressOrderActivity.this, message, Toast.LENGTH_SHORT);
            }
        }, UserManager.getInstance().getCurUser().getId());
    }

    @Subscribe
    public void onEventMainThread(BaseEventBus event)
    {
        switch (event.getMsg())
        {
            case "day":
                day = (int) event.getObject();
                expressOrderShowTimeTv.setText("");
                break;
            case "dayHour":
                dayHour = (int) event.getObject();
                if (dayHour == -1)
                {
                    return;
                }
                expressTimeBeanList = new ExpressTimeBeanListV2();
                expressTimeBeanList.setData((List<ExpressTimeBeanListV2.DataBean>) event.getObject2());
                switch (day)
                {
                    case 1:
                        expressOrderShowTimeTv.setText("已选 " + "今天" + expressTimeBeanList.getData().get(dayHour).getStart() + "-" + expressTimeBeanList.getData().get(dayHour).getEnd());
                        break;
                    case 2:
                        expressOrderShowTimeTv.setText("已选 " + "明天" + expressTimeBeanList.getData().get(dayHour).getStart() + "-" + expressTimeBeanList.getData().get(dayHour).getEnd());
                        break;
                    case 3:
                        expressOrderShowTimeTv.setText("已选 " + "后天" + expressTimeBeanList.getData().get(dayHour).getStart() + "-" + expressTimeBeanList.getData().get(dayHour).getEnd());
                        break;
                }
                ExpressManager.getInstance().initSumPrice(new IHttpCallBackListener()
                {
                    @Override
                    public void success(JSONObject result)
                    {
                        tv_express_order_pay.setEnabled(true);
                        try
                        {
                            expressOrderPaisongfeiTv.setText("¥ " + new DecimalFormat("#0.00").format(result.getDouble("data") / 100));
                            expressOrderPayNumTv.setText("¥ " + new DecimalFormat("#0.00").format(result.getDouble("data") / 100));
                            if (couponInfos != null && couponInfosPosi != -1)
                            {
                                double resultPay = Double.parseDouble(expressOrderPaisongfeiTv.getText().toString().replace("¥", "").trim()) - (double) couponInfos.get(couponInfosPosi).getCoupon() / 100;
                                expressOrderYouhuiTv.setText("¥ " + new DecimalFormat("#0.00").format(couponInfos.get(couponInfosPosi).getCoupon() / 100));
                                expressOrderPayNumTv.setText("¥ " + new DecimalFormat("#0.00").format(resultPay >= 0 ? resultPay : 0.00));

                            }
                        } catch (JSONException e)
                        {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(String message)
                    {
                        UiUtils.ToastInCenter(ExpressOrderActivity.this, message, Toast.LENGTH_SHORT);
                        tv_express_order_pay.setEnabled(false);
                    }
                }, day, expressTimeBeanList.getData().get(dayHour).getId(), adapter.getData().size());
                break;

            case "dayHourId":
                dayHourId = (int) event.getObject();
                break;

            case "finish_pay":
                finish();
                break;

        }
    }

}
